package com.buba.user.utils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.List;

/**
 * 分页助手
 * @auther zcy
 * @date 2021/10/27 14:47
 */
public class MybatisPageHelper {

    /**
     * 将分页的开始页、数量进行封装
     *
     * @param pageRequest
     */
    public static void startPage(PageRequest pageRequest) {
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
    }


    /**
     * 将分页的开始页、数量进行封装
     *
     * @param pageRequest
     */
    public static PageInfo startPage(PageRequest pageRequest, List<?> list) {

        Page page = new Page(pageRequest.getPageNum(), pageRequest.getPageSize());
        //为Page类中的total属性赋值
        int total = list.size();
        page.setTotal(total);
        //计算当前需要显示的数据下标起始值
        int startIndex = (pageRequest.getPageNum() - 1) * pageRequest.getPageSize();
        int endIndex = Math.min(startIndex + pageRequest.getPageSize(),total);
        //从链表中截取需要显示的子链表，并加入到Page
        page.addAll(list.subList(startIndex,endIndex));
        //以Page创建PageInfo
        PageInfo pageInfo = new PageInfo<>(page);
        //将数据传回前端
        return pageInfo;
    }
    /**
     * 生成分页结果集
     *
     * @param list
     * @return
     */
    public static PageResult getPageResult(List<?> list) {
        PageInfo pageInfo = new PageInfo(list);
        PageResult pageResult = new PageResult();
        pageResult.setPageNum(pageInfo.getPageNum());
        pageResult.setPageSize(pageInfo.getPageSize());
        pageResult.setTotalSize(pageInfo.getTotal());
        pageResult.setTotalPages(pageInfo.getPages());
        pageResult.setContent(pageInfo.getList());
        return pageResult;
    }

    /**
     * 生成分页结果集
     *
     * @param pageInfo
     * @return
     */
    public static PageResult getPageResultByPageInfo(PageInfo pageInfo) {
        PageResult pageResult = new PageResult();
        pageResult.setPageNum(pageInfo.getPageNum());
        pageResult.setPageSize(pageInfo.getPageSize());
        pageResult.setTotalSize(pageInfo.getTotal());
        pageResult.setTotalPages(pageInfo.getPages());
        pageResult.setContent(pageInfo.getList());
        return pageResult;
    }

}
